<template>
  <div class="fertilizer-management-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><Crop /></el-icon>
        <span>施肥管理</span>
      </div>
      <div class="page-actions agri-page-actions">
        <el-button type="primary" @click="handleAddRecord">
          <el-icon><Plus /></el-icon> 添加施肥记录
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="agri-card">
      <template #header>
        <div class="card-header">
          <div class="card-title">施肥记录列表</div>
          <div class="card-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索土地或作物"
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 数据列表 -->
      <div class="agri-table-wrapper">
        <el-table :data="filteredFertilizingRecords" border stripe>
          <el-table-column label="土地名称" prop="landName" min-width="120" />
          <el-table-column label="作物类型" prop="cropType" min-width="120" />
          <el-table-column label="肥料名称" prop="fertilizerName" min-width="120" />
          <el-table-column label="施肥日期" min-width="180">
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column label="用量(kg)" prop="amount" min-width="120" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <div class="agri-operations">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleEditRecord(scope.row)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteRecord(scope.row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="filteredFertilizingRecords.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <div class="agri-dialog-wrapper">
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑施肥记录' : '添加施肥记录'"
        width="500px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item label="选择土地" prop="landId">
            <el-select
              v-model="form.landId"
              filterable
              placeholder="请选择土地"
              style="width: 100%"
              @change="handleLandChange"
            >
              <el-option
                v-for="item in lands"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span style="color: #8492a6; font-size: 13px">({{ item.area }}亩)</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="作物类型" prop="cropType">
            <el-select
              v-model="form.cropType"
              filterable
              placeholder="请选择作物类型"
              style="width: 100%"
              :disabled="!form.landId" 
            >
              <el-option
                v-for="item in cropTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              <template #empty>
                <p class="select-empty-hint">{{ form.landId ? '该土地没有种植作物' : '请先选择土地' }}</p>
              </template>
            </el-select>
          </el-form-item>

          <el-form-item label="肥料名称" prop="fertilizerId">
            <el-select
              v-model="form.fertilizerId"
              filterable
              placeholder="请选择肥料"
              style="width: 100%"
            >
              <el-option
                v-for="item in fertilizerInventory"
                :key="item.itemId"
                :label="item.name"
                :value="item.itemId"
              >
                <span>{{ item.name }}</span>
                <span style="color: #8492a6; font-size: 13px">(库存: {{ item.quantity }}{{ item.unit }})</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="施肥日期" prop="date">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="用量(kg)" prop="amount">
            <el-input-number
              v-model="form.amount"
              :min="0"
              :max="1000"
              :step="0.5"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="备注" prop="note">
            <el-input
              v-model="form.note"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{ isEdit ? '更新' : '添加' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
    >
      <span>确定要删除这条施肥记录吗？此操作不可撤销。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button
            type="danger"
            @click="confirmDelete"
            :loading="deleteLoading"
          >
            确定删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Crop, Plus, Edit, Delete, Search } from '@element-plus/icons-vue';
import { useFarmerStore } from '../../store';
import { format } from 'date-fns';

// 获取状态管理
const farmerStore = useFarmerStore();

// 表格数据和分页
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');

// 对话框控制
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const submitLoading = ref(false);
const deleteLoading = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const currentRecordId = ref(null);

// 表单数据
const form = reactive({
  landId: '',
  cropType: '',
  fertilizerId: '',
  date: '',
  amount: 0,
  note: ''
});

// 表单验证规则
const rules = {
  landId: [{ required: true, message: '请选择土地', trigger: 'change' }],
  cropType: [{ required: true, message: '请选择作物类型', trigger: 'change' }],
  fertilizerId: [{ required: true, message: '请选择肥料', trigger: 'change' }],
  date: [{ required: true, message: '请选择施肥日期', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入用量', trigger: 'blur' },
    { type: 'number', min: 0, message: '用量必须大于0', trigger: 'blur' }
  ]
};

// 选项数据
const lands = ref([]);
const cropTypes = ref([]);
const fertilizerInventory = ref([]);
const fertilizingRecords = ref([]);

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  return format(new Date(date), 'yyyy-MM-dd');
};

// 过滤后的施肥记录
const filteredFertilizingRecords = computed(() => {
  if (!searchQuery.value) {
    return fertilizingRecords.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return fertilizingRecords.value.filter(record => {
    return record.landName.toLowerCase().includes(query) ||
      record.cropType.toLowerCase().includes(query) ||
      record.fertilizerName.toLowerCase().includes(query);
  });
});

// 处理土地变更
const handleLandChange = async (landId) => {
  // 重置作物类型
  form.cropType = '';
  // 清空作物类型列表
  cropTypes.value = [];
  
  if (!landId) return;
  
  try {
    // 从选中的土地信息中直接获取当前种植的作物
    const selectedLand = lands.value.find(land => land.id === landId);
    console.log('选中的土地信息:', selectedLand);
    
    // 创建作物类型集合
    const cropTypeSet = new Set();
    
    // 1. 如果土地有currentCrop，添加到集合，但不立即返回
    if (selectedLand && selectedLand.currentCrop) {
      console.log('从土地信息获取作物类型:', selectedLand.currentCrop);
      cropTypeSet.add(selectedLand.currentCrop);
    }
    
    // 2. 尝试从种植记录中获取更多作物类型
    const plantings = await farmerStore.fetchPlantings();
    console.log('获取到所有种植记录:', plantings);
    
    // 打印每条记录的完整信息，帮助诊断问题
    plantings.forEach((p, index) => {
      console.log(`种植记录[${index}]:`, JSON.stringify(p));
    });
    
    // 获取所有与该土地相关的种植记录，不限制状态
    let landPlantings = plantings.filter(p => p.landId === landId);
    
    // 输出所有找到的相关种植记录
    console.log(`土地ID ${landId} 相关的所有种植记录数量: ${landPlantings.length}`);
    landPlantings.forEach((p, index) => {
      console.log(`该土地种植记录[${index}]:`, JSON.stringify(p));
    });
    
    // 如果该土地有种植记录
    if (landPlantings.length > 0) {
      // 检查所有可能的字段名
      const possibleCropFields = ['cropType', 'cropName', 'crop', 'cropVariety', 'plantType', 'plantName'];
      
      landPlantings.forEach(planting => {
        console.log('处理种植记录:', planting);
        
        // 检查所有可能的字段
        for (const field of possibleCropFields) {
          if (planting[field] && typeof planting[field] === 'string' && planting[field].trim() !== '') {
            console.log(`发现作物信息 [${field}]: ${planting[field]}`);
            cropTypeSet.add(planting[field]);
          }
        }
      });
    } else {
      console.log('该土地没有任何种植记录');
      // 尝试使用土地的其他属性可能包含的作物信息
      if (selectedLand) {
        const landFields = Object.keys(selectedLand);
        console.log('土地包含的所有字段:', landFields);
        
        // 检查土地对象中可能包含作物信息的字段
        const cropRelatedFields = ['crop', 'plantingInfo', 'cropInfo', 'plantInfo'];
        for (const field of cropRelatedFields) {
          if (selectedLand[field] && typeof selectedLand[field] === 'string') {
            console.log(`从土地的${field}字段找到作物信息:`, selectedLand[field]);
            cropTypeSet.add(selectedLand[field]);
          }
        }
      }
    }
    
    console.log('收集到的作物类型集合:', [...cropTypeSet]);
    
    // 转换为下拉框选项格式
    cropTypes.value = Array.from(cropTypeSet).map(type => ({
      label: type,
      value: type
    }));
    
    console.log('最终的作物类型选项:', cropTypes.value);
    
    // 默认选择土地当前种植的作物类型，或者最新记录的作物类型
    if (cropTypes.value.length > 0) {
      if (selectedLand && selectedLand.currentCrop) {
        // 优先使用土地当前种植的作物
        form.cropType = selectedLand.currentCrop;
      } else if (landPlantings.length > 0) {
        // 没有当前作物时，使用最新记录的作物
        const latestPlanting = landPlantings.sort((a, b) => {
          const dateA = new Date(b.plantingDate || b.createTime || 0);
          const dateB = new Date(a.plantingDate || a.createTime || 0);
          return dateA - dateB;
        })[0];
        
        // 检查所有可能的字段
        const possibleCropFields = ['cropType', 'cropName', 'crop', 'cropVariety', 'plantType', 'plantName'];
        for (const field of possibleCropFields) {
          if (latestPlanting[field] && typeof latestPlanting[field] === 'string' && latestPlanting[field].trim() !== '') {
            form.cropType = latestPlanting[field];
            console.log('设置默认作物类型:', form.cropType);
            break;
          }
        }
      }
    }
  } catch (error) {
    console.error('获取土地种植信息失败', error);
    ElMessage.warning('获取土地种植信息失败，请手动选择作物类型');
  }
};

// 处理添加记录
const handleAddRecord = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 处理编辑记录
const handleEditRecord = (row) => {
  isEdit.value = true;
  currentRecordId.value = row.id;
  Object.assign(form, {
    landId: row.landId,
    cropType: row.cropType,
    fertilizerId: row.fertilizerId,
    date: new Date(row.date),
    amount: row.amount,
    note: row.note || ''
  });
  dialogVisible.value = true;
};

// 处理删除记录
const handleDeleteRecord = (row) => {
  currentRecordId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!currentRecordId.value) return;
  
  try {
    deleteLoading.value = true;
    // TODO: 调用删除API
    await farmerStore.deleteFertilizingRecord(currentRecordId.value);
    ElMessage.success('施肥记录删除成功');
    fetchFertilizingRecords();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error('删除失败', error);
    ElMessage.error('删除失败: ' + (error.message || '未知错误'));
  } finally {
    deleteLoading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      submitLoading.value = true;
      
      // 准备提交数据
      const submitData = {
        landId: form.landId,
        cropType: form.cropType,
        fertilizerId: form.fertilizerId,
        date: form.date,
        amount: form.amount,
        note: form.note
      };
      
      if (isEdit.value && currentRecordId.value) {
        // 更新记录
        await farmerStore.updateFertilizingRecord(currentRecordId.value, submitData);
        ElMessage.success('施肥记录更新成功');
      } else {
        // 添加记录
        await farmerStore.addFertilizingRecord(submitData);
        ElMessage.success('施肥记录添加成功');
      }
      
      dialogVisible.value = false;
      fetchFertilizingRecords();
    } catch (error) {
      console.error('提交失败', error);
      ElMessage.error('提交失败: ' + (error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    landId: '',
    cropType: '',
    fertilizerId: '',
    date: new Date(),
    amount: 0,
    note: ''
  });
};

// 分页处理
const handlePageChange = (val) => {
  currentPage.value = val;
};

// 获取施肥记录
const fetchFertilizingRecords = async () => {
  loading.value = true;
  try {
    const records = await farmerStore.fetchFertilizingRecords();
    // 确保记录存在且为数组
    if (records && Array.isArray(records)) {
      fertilizingRecords.value = records.map(record => {
        // 查找对应的土地和肥料名称
        const land = lands.value.find(l => l.id === record.landId);
        const fertilizer = fertilizerInventory.value.find(f => f.itemId === record.fertilizerId) || 
                         { name: record.fertilizerName || '未知肥料' };
        
        return {
          ...record,
          landName: land ? land.name : '未知土地',
          fertilizerName: fertilizer.name || record.fertilizerName || '未知肥料'
        };
      });
    } else {
      fertilizingRecords.value = [];
      console.log('没有获取到施肥记录数据');
    }
  } catch (error) {
    console.error('获取施肥记录失败', error);
    ElMessage.error('获取施肥记录失败');
    fertilizingRecords.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取土地列表
const fetchLands = async () => {
  try {
    const landsData = await farmerStore.fetchLands();
    lands.value = landsData;
  } catch (error) {
    console.error('获取土地列表失败', error);
  }
};

// 获取肥料库存
const fetchFertilizerInventory = async () => {
  try {
    const inventory = await farmerStore.fetchFertilizerInventory();
    fertilizerInventory.value = inventory;
  } catch (error) {
    console.error('获取肥料库存失败', error);
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  await Promise.all([
    fetchLands(),
    fetchFertilizerInventory()
  ]);
  fetchFertilizingRecords();
});
</script>

<style scoped>
.fertilizer-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.page-actions {
  display: flex;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-input {
    width: 100%;
    margin-top: 10px;
  }
}

.select-empty-hint {
  padding: 10px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style> 